/**
 * 字段转换系统使用示例
 * 展示如何在实际项目中使用字段转换功能
 */

import { 
  stockPlanTransformer,
  FieldTransformer,
  STOCK_PLAN_FIELD_MAPPING,
  transformObjectToCamel,
  transformObjectToSnake
} from '../utils/fieldTransform';

// ===== 示例1: 基础使用 =====
console.log('=== 示例1: 基础字段转换 ===');

// 模拟从数据库获取的数据（snake_case格式）
const rawDbData = {
  id: 'stock_plan_001',
  user_id: 'user_123456',
  stock_code: '000001',
  stock_name: '平安银行',
  current_price: 12.50,
  max_drawdown: -30.5,
  total_shares: 1000,
  buy_times: 5,
  strategy: 'pyramid',
  average_price: 11.80,
  total_amount: 11800.00,
  created_at: '2025-09-29T10:00:00.000Z',
  updated_at: '2025-09-29T11:00:00.000Z'
};

// 转换为前端格式
const frontendData = stockPlanTransformer.fromDB(rawDbData);
console.log('数据库数据转换为前端格式:', frontendData);

// ===== 示例2: 批量数据转换 =====
console.log('\n=== 示例2: 批量数据转换 ===');

const batchDbData = [
  rawDbData,
  {
    ...rawDbData,
    id: 'stock_plan_002',
    stock_code: '000002',
    stock_name: '万科A',
    current_price: 18.20
  }
];

const batchFrontendData = stockPlanTransformer.fromDBBatch(batchDbData);
console.log('批量转换结果:', batchFrontendData);

// ===== 示例3: 前端数据保存到数据库 =====
console.log('\n=== 示例3: 前端数据转换为数据库格式 ===');

const newPlanData = {
  id: 'stock_plan_003',
  userId: 'user_789012',
  stockCode: '000003',
  stockName: '中国平安',
  currentPrice: 45.80,
  maxDrawdown: -25.3,
  totalShares: 200,
  buyTimes: 3,
  strategy: 'equal',
  averagePrice: 44.20,
  totalAmount: 8840.00,
  minLots: 1,
  lotSize: 100,
  stockType: '股票',
  trackingIndex: '',
  managementFee: 0,
  riskLevel: '中等风险',
  maxLoss: -22.1,
  createdAt: new Date().toISOString(),
  updatedAt: new Date().toISOString()
};

const dbFormatData = stockPlanTransformer.toDB(newPlanData);
console.log('前端数据转换为数据库格式:', dbFormatData);

// ===== 示例4: 自定义业务模块的字段转换 =====
console.log('\n=== 示例4: 自定义业务模块字段转换 ===');

// 假设我们有一个基金投资计划模块
const FUND_PLAN_FIELD_MAPPING = {
  id: 'id',
  userId: 'user_id',
  fundCode: 'fund_code',
  fundName: 'fund_name',
  currentNav: 'current_nav',
  investmentAmount: 'investment_amount',
  purchaseDate: 'purchase_date',
  expectedReturn: 'expected_return',
  riskRating: 'risk_rating',
  createdAt: 'created_at',
  updatedAt: 'updated_at'
};

const fundPlanTransformer = new FieldTransformer(FUND_PLAN_FIELD_MAPPING);

const fundDbData = {
  id: 'fund_plan_001',
  user_id: 'user_123456',
  fund_code: '110022',
  fund_name: '易方达消费行业股票',
  current_nav: 3.2580,
  investment_amount: 5000.00,
  purchase_date: '2025-09-29',
  expected_return: 8.5,
  risk_rating: 'R4',
  created_at: '2025-09-29T10:00:00.000Z',
  updated_at: '2025-09-29T11:00:00.000Z'
};

const fundFrontendData = fundPlanTransformer.fromDB(fundDbData);
console.log('基金计划数据转换:', fundFrontendData);

// ===== 示例5: 在API调用中使用 =====
console.log('\n=== 示例5: API调用中的使用示例 ===');

// 模拟API服务类
class StockPlanApiService {
  // 获取投资计划列表
  async getStockPlans(): Promise<any[]> {
    // 模拟API调用
    const apiResponse = [rawDbData, batchDbData[1]];
    
    // 转换字段格式
    return stockPlanTransformer.fromDBBatch(apiResponse);
  }
  
  // 保存投资计划
  async saveStockPlan(planData: any): Promise<void> {
    // 转换为数据库格式
    const dbData = stockPlanTransformer.toDB(planData);
    
    // 模拟API调用
    console.log('发送到API的数据:', dbData);
    
    // 实际项目中这里会调用真实的API
    // await fetch('/api/stock-plans', { method: 'POST', body: JSON.stringify(dbData) });
  }
}

const apiService = new StockPlanApiService();

// 使用示例
(async () => {
  try {
    const plans = await apiService.getStockPlans();
    console.log('获取到的投资计划（已转换格式）:', plans);
    
    await apiService.saveStockPlan(newPlanData);
    console.log('投资计划保存成功');
  } catch (error) {
    console.error('API调用失败:', error);
  }
})();

// ===== 示例6: 表单数据处理 =====
console.log('\n=== 示例6: 表单数据处理示例 ===');

// 模拟表单提交处理
function handleFormSubmit(formData: any) {
  console.log('原始表单数据:', formData);
  
  // 转换为数据库格式进行保存
  const dbData = stockPlanTransformer.toDB(formData);
  console.log('转换后的数据库格式:', dbData);
  
  // 这里可以调用保存API
  return dbData;
}

// 模拟表单数据
const formData = {
  stockCode: '000001',
  stockName: '平安银行',
  currentPrice: 12.50,
  totalAmount: 10000,
  buyTimes: 5,
  strategy: 'pyramid'
};

handleFormSubmit(formData);

// ===== 示例7: 错误处理和边界情况 =====
console.log('\n=== 示例7: 错误处理和边界情况 ===');

// 处理null和undefined
console.log('处理null:', stockPlanTransformer.fromDB(null));
console.log('处理undefined:', stockPlanTransformer.fromDB(undefined));

// 处理空对象
console.log('处理空对象:', stockPlanTransformer.fromDB({}));

// 处理嵌套对象
const nestedData = {
  plan_info: {
    plan_id: 'nested_001',
    user_id: 'user_123'
  },
  stock_list: [
    { stock_code: '000001', current_price: 12.50 },
    { stock_code: '000002', current_price: 18.20 }
  ]
};

console.log('嵌套对象转换:', transformObjectToCamel(nestedData));

// ===== 示例8: 性能测试 =====
console.log('\n=== 示例8: 性能测试 ===');

const performanceTest = () => {
  const testData = Array.from({ length: 1000 }, (_, i) => ({
    ...rawDbData,
    id: `plan_${i}`,
    stock_code: `00000${i % 10}`
  }));
  
  console.time('批量转换1000条数据');
  const converted = stockPlanTransformer.fromDBBatch(testData);
  console.timeEnd('批量转换1000条数据');
  
  console.log(`转换完成，共处理 ${converted.length} 条数据`);
};

performanceTest();

export {
  stockPlanTransformer,
  fundPlanTransformer,
  StockPlanApiService,
  FUND_PLAN_FIELD_MAPPING
};